//
//  KeyCache
//
//  Created by Caue W. on 2011-03-07.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//
package time.types.ds;
import time.types.ds.KeyHash;
import time.types.ds.KeyStore;

class KeyCache implements KeyManager
{	
	var byObj:ObjectHash<Dynamic, Key<Dynamic>>;
	var byKey:KeyHash<Dynamic>;
	
	public function new()
	{
		byObj = new ObjectHash();
		byKey = new KeyHash();
	}
	
	public function getKey<T>(obj : T) : Null<Key<T>>
	{
		return cast byObj.get(obj);
	}
	
	public function dispose<T>(obj : T) : Bool
	{
		var k = byObj.get(obj);
		if (k == null)
			return false;
		
		byKey.remove(k);
		byObj.remove(obj);
		
		return true;
	}
	
	public function disposeAll<T>(objs : Iterable<T>) : Bool
	{
		var ok = true;
		for (obj in objs)
		{
			var k = byObj.get(obj);
			if (k == null)
			{
				ok = false;
				continue;
			}

			byKey.remove(k);
			byObj.remove(obj);
		}
		
		return ok;
	}
	
	public function getWithKey<T>(k:Key<T>) : Null<T>
	{
		return byKey.get(k);
	}
	
	public function setKey<T>(obj : T, k : Key<T>) : Void
	{
		byKey.set(k, obj);
		byObj.set(obj, k);
	}
}